import os

from coin.strategy.mm.subscription import SubscriptionRequest
import coin.feed.fastfeed.feed_cache_gen as fcg


class FeedCacheJob(object):
  def __init__(self, trading_date, machine, subscription_key, worker_id, root_dir):
    self.trading_date = trading_date
    self.machine = machine
    self.sub_key = subscription_key
    self.worker_id = worker_id
    self.root_dir = os.path.expanduser(root_dir)

  @property
  def root_dir(self):
    return os.path.expanduser(self.root_dir)

  @property
  def filename(self):
    return os.path.join(
        self.root_dir,
        "%s.log" % "_".join((self.trading_date.strftime("%Y%m%d"),
                             self.machine,
                             self.sub_key.to_str(),
                             self.worker_id)))

  def serialize(self):
    feed_cache_gen = fcg.FeedCacheGenerator(machine=self.machine,
                                            date=self.trading_date,
                                            sub_req=self.sub_key,
                                            worker_id=self.worker_id,
                                            feed_cache_dir=self.root_dir)
    feed_cache_gen.run()
    with open(self.filename, 'w') as fwrite:
      fwrite.write("done")

  def deserialize(self):
    if not os.path.exists(self.filename):
      self.serialize()
    return True


def run_feed_cache_if_none(trading_date, machine, subscription_key, worker_id):
  return FeedCacheJob(trading_date, machine, subscription_key, worker_id).deserialize()
